<template>
  <div class="app-container">
    <div v-show="!detailInfo.visible && !detailListInfo.visible">
      <!-- 条件栏 -->
      <div class="filter-wrapper">
        <NewPageFilter
          v-model:query="filterInfo.query.queryMap"
          :query-more-json="true"
          :filter-list="filterInfo.searchList"
          :filter-btn="filterInfo.searchBtn"
          :clear-type="clearType"
          :slip-select-request="slipSelectRequest"
        >
        </NewPageFilter>
        <el-button @click="detailListInfo.visible = true">明细页</el-button>
      </div>
      <div class="filter-wrapper">
        <NewPageFilter :filter-btn="filterInfo.btnList">
          <template v-slot:filter-accept>
            <el-button :disabled="!canAccept" @click="accept"
              >一键验收</el-button
            >
          </template>
          <template v-slot:filter-setUse>
            <el-button :disabled="!canUse" @click="setUse"
              >设置为已使用</el-button
            >
          </template>
          <template v-slot:filter-setNotUse>
            <el-button :disabled="!canNotUse" @click="setNotUse"
              >设置为未使用</el-button
            >
          </template>
        </NewPageFilter>
        <div class="display-flex">
          <el-button @click="preferenceInfo.visible = true">偏好设置</el-button>
        </div>
      </div>
      <!-- 表格 -->
      <table-container
        :refresh="tableInfo.refresh"
        :init-curpage="tableInfo.initCurpage"
        v-model:data="tableInfo.data"
        :api="tableInfo.api"
        :query="filterInfo.query"
        :field-list="tableInfo.fieldList"
        :handle="tableInfo.handle"
        :row-class-name="tableRowClassName"
        @sortChange="sortChange"
        @handleEvent="handleEvent"
        @pageInfo="pageInfo"
      >
        <template v-slot:col-orderNo="scope">
          <span
            v-if="$permission('withTableAcceptOrder:details')"
            class="slip-edit"
            @click="showDetail(scope.row)"
            >{{ scope.row.orderNo || '-' }}</span
          >
          <span v-else>{{ scope.row.orderNo || '-' }}</span>
        </template>
      </table-container>
    </div>
    <Details
      v-if="detailInfo.visible"
      :id="detailInfo.id"
      v-model:visible="detailInfo.visible"
      @returnBack="getList"
    />
    <detailList
      v-if="detailListInfo.visible"
      v-model:visible="detailListInfo.visible"
      @callback="getList"
    ></detailList>
    <set-preference
      v-if="preferenceInfo.visible"
      v-model:visible="preferenceInfo.visible"
      :search-list="filterInfo.searchList"
      :field-list="tableInfo.fieldList"
      :customize-user-v-o="filterInfo.query.customizeUserVO"
      :group-level-show="false"
      @callback="setPreferenceCallback"
    />
    <advanced-search
      v-if="advancedSearchInfo.visible"
      v-model:visible="advancedSearchInfo.visible"
      v-model:form-data="advancedSearchInfo.data"
      :field-list="tableInfo.fieldList"
      @callback="advancedSearchCallback"
    />
    <page-dialog
      v-show="dialogInfo.visible"
      :title="dialogInfo.title"
      v-model:visible="dialogInfo.visible"
      :width="dialogInfo.width"
      :bt-loading="dialogInfo.btLoading"
      :bt-list="dialogInfo.btList"
    >
      <div class="asset-msg">
        <div class="asset-msg-label">
          <i class="el-icon-warning"></i>{{ dialogInfo.msg }}：
        </div>
        <el-radio-group v-model="dialogInfo.flag">
          <el-radio :label="true">当前页数据</el-radio>
          <el-radio :label="false">全部页数据</el-radio>
        </el-radio-group>
      </div>
    </page-dialog>
  </div>
</template>

<script setup name="withTableAcceptOrder">
import TableContainer from '@/components/TableContainer/index'
import PageDialog from '@/components/PageDialog/index'
import {
  withTableAcceptOrderNnused,
  withTableAcceptOrderUsed,
  withTableAcceptOrderAcceptance,
  getWithTableAcceptOrderPage,
  withTableAcceptOrderPrintOrderList,
  withTableAcceptOrderExcelOrderList,
} from '@/api/withTable.js'
import { fatchTemplateByCode } from '@/api/base'
import Details from './details'
import { getCustomizeSetting, updateUserCustomize } from '@/api/customize'

const { proxy } = getCurrentInstance()
const emit = defineEmits()
const SetPreference = defineAsyncComponent(() =>
  import('@/components/SetPreference/index')
)
const AdvancedSearch = defineAsyncComponent(() =>
  import('@/components/AdvancedSearch/index')
)
const detailList = defineAsyncComponent(() => import('./detailList'))

const clearType = ref(true)
const slipSelectRequest = ref(true)
const time = ref([])
const dialogInfo = reactive({
  visible: false,
  title: '提示',
  btLoading: false,
  type: '',
  msg: '',
  width: '400px',
  flag: true,
  btList: [
    { label: '关闭', event: handleClose, show: true },
    {
      label: '打印',
      type: 'primary',
      event: checkConfirm,
      show: true,
    },
  ],
})
// 过滤相关配置
const filterInfo = reactive({
  sortArr: [],
  copyQueryMap: {},
  query: {
    customizeUserVO: {},
    queryMap: {
      deptAuth: {
        asTbName: 'with_table_accept_order',
        columnName: 'dept_id',
        queryType: 'IN',
        queryCategory: 'AND',
        value: 'deptAuth',
      },
      supplierAuth: {
        asTbName: 'with_table_accept_order',
        columnName: 'supplier_id',
        queryType: 'IN',
        queryCategory: 'AND',
        value: 'supplierAuth',
      },
    },
  },
  searchList: [],
  searchBtn: [
    { type: 'button', label: '搜索', event: search },
    { type: 'button', label: '高级查询', event: advancedSearchShow },
    { type: 'button', label: '重置', event: clearSearch },
  ],
  btnList: [
    {
      type: 'slot',
      value: 'accept',
      show: proxy.$permission('withTableAcceptOrder:accept'),
    },
    {
      type: 'slot',
      value: 'setUse',
      show: proxy.$permission('withTableAcceptOrder:setUse'),
    },
    {
      type: 'slot',
      value: 'setNotUse',
      show: proxy.$permission('withTableAcceptOrder:setNotUse'),
    },
    {
      label: '打印',
      type: 'button',
      event: print,
      show: proxy.$permission('withTableAcceptOrder:printOrderList'),
    },
    {
      label: '导出excel',
      type: 'button',
      event: exportExcel,
      show: proxy.$permission('withTableAcceptOrder:excelOrderList'),
    },
  ],
})
// 表格相关
const tableInfo = reactive({
  refresh: 1,
  initCurpage: 1,
  data: [],
  api: undefined,
  selections: [],
  fieldList: [],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '120',
    btList: [
      {
        label: '验收',
        event: accept,
        show: proxy.$permission('withTableAcceptOrder:accept'),
        ifRender: function (row) {
          return row.acceptStatus === 0
        },
      },
      {
        label: '设置为已使用',
        event: setUse,
        show: proxy.$permission('withTableAcceptOrder:setUse'),
        ifRender: function (row) {
          return row.useStatus === 0
        },
      },
      {
        label: '设置为未使用',
        event: setNotUse,
        show: proxy.$permission('withTableAcceptOrder:setNotUse'),
        ifRender: function (row) {
          return row.useStatus === 1
        },
      },
    ],
  },
})
const modifyInfo = reactive({
  visible: false,
  orderId: '',
  title: '',
})
const detailInfo = reactive({
  visible: false,
  id: '',
})
const detailListInfo = reactive({
  visible: false,
})
const preferenceInfo = reactive({
  visible: false,
})
const advancedSearchInfo = reactive({
  visible: false,
  data: {},
})

let page = reactive({
  curPage: 1, // 当前页
  pageSize: 20, // 每页条数
})

const canAccept = computed(() => {
  return (
    tableInfo.selections.length &&
    !tableInfo.selections.filter((item) => item.acceptStatus !== 0).length
  )
})
const canUse = computed(() => {
  return (
    tableInfo.selections.length &&
    !tableInfo.selections.filter((item) => item.useStatus !== 0).length
  )
})
const canNotUse = computed(() => {
  return (
    tableInfo.selections.length &&
    !tableInfo.selections.filter((item) => item.useStatus !== 1).length
  )
})

let obj = {
  acceptStatusValue: {
    label: '状态',
    value: 'acceptStatusValue',
    asValue: 'acceptStatus',
    componentType: 'select-model',
    code: 'with_table_accept_accept_status',
    show: false,
    hidden: true,
  },
  useStatusValue: {
    label: '状态',
    value: 'useStatusValue',
    asValue: 'useStatus',
    componentType: 'select-model',
    code: 'with_table_accept_use_status',
    show: false,
    hidden: true,
  },
  preQty: {
    label: '已使用数量',
    value: 'preQty',
    type: 'column',
    componentType: 'column',
    formatter: proxy.$fn.qtyFixedFormatter,
    show: false,
    hidden: true,
  },
}
tableInfo.fieldList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  ...proxy.$fn.deepClone(obj),
})
filterInfo.searchList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  ...proxy.$fn.deepClone(obj),
})
getCustomize()

function pageInfo(obj) {
  page = obj
}
function handleClose() {
  dialogInfo.visible = false
}
function checkConfirm() {
  if (dialogInfo.type === 'excel') {
    exportExcelList()
  } else if (dialogInfo.type === 'print') {
    printList()
  }
  dialogInfo.visible = false
  dialogInfo.msg = ''
}
function exportExcel() {
  dialogInfo.visible = true
  dialogInfo.type = 'excel'
  dialogInfo.msg = '请选择数据导出范围'
  dialogInfo.btList[1].label = '导出'
  dialogInfo.flag = true
}
function exportExcelList() {
  let params = {
    ...filterInfo.query,
    ...page,
    page: dialogInfo.flag,
  }
  withTableAcceptOrderExcelOrderList(params).then((resp) => {
    if (resp) {
      proxy.$fn.parseExcel(resp)
    }
  })
}
async function print() {
  dialogInfo.visible = true
  dialogInfo.type = 'print'
  dialogInfo.msg = '请选择当数据打印范围'
  dialogInfo.btList[1].label = '打印'
  dialogInfo.flag = true
}
//打印
function printList() {
  fatchTemplateByCode({
    resourceCode: 'withTableAcceptOrder:printOrderList',
    isDefault: 1,
  }).then((res) => {
    if (res && res.success) {
      let temp = proxy.$fn.getPrintTemp(res.data[0])
      getPrintData(temp, dialogInfo.flag)
    }
  })
}
function getPrintData(temp, flag) {
  let query = {
    customizeDto: filterInfo.query,
  }
  let params = {
    ...query,
    ...page,
    page: flag,
  }
  withTableAcceptOrderPrintOrderList(params).then((res) => {
    if (res.success && res) {
      let data = proxy.$fn.deepClone(res.data)
      let newData = data.map((item) => {
        return {
          ...item,
          ...item.orderInfo,
        }
      })
      proxy.$lodop.preview(temp, newData)
    }
  })
}
function returnModify() {
  if (modifyInfo.orderId) {
    getList()
  } else {
    search()
  }
}
async function setPreferenceCallback(obj) {
  updateUserCustomize(obj.customizeUserVO).then((res) => {
    if (res && res.success) {
      getCustomize(!slipSelectRequest.value)
    }
  })
}
function advancedSearchShow() {
  advancedSearchInfo.visible = true
}
async function advancedSearchCallback(obj) {
  let arr = [
    {
      asTbName: 'with_table_order',
      columnName: 'dept_id',
      queryType: 'IN',
      queryCategory: 'AND',
      value: 'deptAuth',
    },
    {
      asTbName: 'with_table_order',
      columnName: 'supplier_id',
      queryType: 'IN',
      queryCategory: 'AND',
      value: 'supplierAuth',
    },
  ]
  filterInfo.query.queryMap = {}
  filterInfo.query.queryDtoList = [...obj.queryDtoList, ...arr]
  advancedSearchInfo.data = obj.data
  await getList()
  clearType.value = !clearType.value
  filterInfo.query.queryMap = proxy.$fn.deepClone(filterInfo.copyQueryMap)
}
// 获取列表
async function getList() {
  tableInfo.refresh = Math.random()
}
// 搜索
function search() {
  // 重置分页
  advancedSearchInfo.data = {}
  filterInfo.query.queryDtoList = []
  tableInfo.initCurpage = Math.random()
  tableInfo.refresh = Math.random()
}

//验收
function accept(row = undefined) {
  let ids = []
  if (row && row.id) {
    ids = [row.id]
  } else {
    ids = tableInfo.selections.map((item) => item.id)
  }
  withTableAcceptOrderAcceptance(ids).then((res) => {
    if (res && res.success) {
      getList()
    }
  })
}
//已使用
function setUse(row = undefined) {
  let ids = []
  if (row && row.id) {
    ids = [row.id]
  } else {
    ids = tableInfo.selections.map((item) => item.id)
  }
  withTableAcceptOrderUsed(ids).then((res) => {
    if (res && res.success) {
      getList()
    }
  })
}
function setNotUse(row = undefined) {
  //未使用
  let ids = []
  if (row && row.id) {
    ids = [row.id]
  } else {
    ids = tableInfo.selections.map((item) => item.id)
  }
  withTableAcceptOrderNnused(ids).then((res) => {
    if (res && res.success) {
      getList()
    }
  })
}

//展示明细
function showDetail(row) {
  sessionStorage.setItem('storeRowId', row.id)
  detailInfo.id = row.id
  detailInfo.visible = true
}
function tableRowClassName({ row }) {
  let rowId = sessionStorage.getItem('storeRowId')
  if (rowId && row.id === Number(rowId)) {
    return 'check-row'
  }
  return ''
}
// 触发事件
function handleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      tableInfo.selections = data
      break
  }
}
function clearSearch() {
  clearType.value = !clearType.value
  advancedSearchInfo.data = {}
  filterInfo.query.queryMap = proxy.$fn.deepClone(filterInfo.copyQueryMap)
  search()
}
function getCustomize(_slipSelectRequest = true) {
  let param = {
    tableKey:
      'withTableAcceptOrderList-com.slip.spd.entity.vo.withtable.WithTableAcceptOrderVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      filterInfo.query.customizeUserVO = data
      tableInfo.fieldList = proxy.$fn.setFieldList(
        tableInfo.fieldList,
        data.detail
      )
      let searchInfo = proxy.$fn.setSearchList(
        filterInfo.searchList,
        data.detail
      )
      filterInfo.query.queryMap = {
        ...searchInfo.queryMap,
        ...filterInfo.query.queryMap,
      }
      filterInfo.searchList = searchInfo.searchList
      filterInfo.searchList.forEach((item) => {
        item.event = search
      })
      filterInfo.copyQueryMap = proxy.$fn.deepClone(filterInfo.query.queryMap)
      slipSelectRequest.value = _slipSelectRequest
      tableInfo.api = getWithTableAcceptOrderPage
      getList()
    }
  })
}
function sortChange(column) {
  if (filterInfo.query.customizeUserVO.head.sortType === 0) {
    let arr = proxy.$fn.sortChange(column, filterInfo.sortArr)
    filterInfo.sortArr = arr
    filterInfo.query.sortString = arr.length ? arr.toString() : ''
    getList()
  }
}
</script>

<style scoped></style>
